package qq2564874169.tuaotuao.fx;

import java.util.Objects;

public class Var<T> {
    private T value;

    public Var(T init) {
        value = init;
    }

    public Var() {

    }

    public T get() {
        return get(null);
    }

    public synchronized T get(T def) {
        return value != null ? value : def;
    }

    public boolean isNull() {
        return value == null;
    }

    public synchronized Var<T> set(T value) {
        this.value = value;
        return this;
    }

    public synchronized T trySet(T oldValue, T newValue) {
        if (this.value == null) {
            this.value = newValue;
            return this.value;
        }
        if (this.value.equals(oldValue)) {
            this.value = newValue;
        }
        return this.value;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Var<?> var = (Var<?>) o;

        return Objects.equals(value, var.value);
    }

    @Override
    public int hashCode() {
        return value != null ? value.hashCode() : 0;
    }
}
